package hn.cch.security.controller;

import hn.cch.security.entity.Department;
import hn.cch.security.entity.Role;
import hn.cch.security.entity.User;
import hn.cch.security.repository.DepartmentRepository;
import hn.cch.security.repository.RoleRepository;
import hn.cch.security.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    private static Logger logger = LoggerFactory.getLogger(UserController
            .class);

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private RoleRepository roleRepository;


    @RequestMapping("/index")
    public String index(ModelMap model, Principal user) throws Exception {
        Authentication authentication = (Authentication) user;
        List<String> userroles = new ArrayList<>();

        for (GrantedAuthority grantedAuthority : authentication
                .getAuthorities()) {
            userroles.add(grantedAuthority.getAuthority());
        }

        boolean newrole = false, editrole = false, deleterole = false;
        String urlroles = "/**/new/**=role,vip;/**/edit/**=role;" +
                "/**/delete/**=role";
        if (!StringUtils.isEmpty(urlroles)) {
            String[] resouces = urlroles.split(";");
            for (String resource : resouces) {
                String[] urls = resource.split("=");
                if (urls[0].indexOf("new") > 0) {
                    String[] newroles = urls[1].split(",");
                    for (String str : newroles) {
                        str = str.trim();
                        if (userroles.contains(str)) {
                            newrole = true;
                            break;
                        }
                    }
                } else if (urls[0].indexOf("edit") > 0) {
                    String[] editoles = urls[1].split(",");
                    for (String str : editoles) {
                        str = str.trim();
                        if (userroles.contains(str)) {
                            editrole = true;
                            break;
                        }
                    }
                } else if (urls[0].indexOf("delete") > 0) {
                    String[] deleteroles = urls[1].split(",");
                    for (String str : deleteroles) {
                        str = str.trim();
                        if (userroles.contains(str)) {
                            deleterole = true;
                            break;
                        }
                    }
                }
            }
        }

        model.addAttribute("newrole", newrole);
        model.addAttribute("editrole", editrole);
        model.addAttribute("deleterole", deleterole);

        model.addAttribute("user", user);
        return "user/index";
    }

    @RequestMapping(value = "/{id}")
    public String show(ModelMap model, @PathVariable Long id) {
        User user = userRepository.findOne(id);
        model.addAttribute("user", user);
        return "user/show";
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public Page<User> getList(User user) {

        Pageable pageable = new PageRequest(0, 4, new Sort(Sort.Direction
                .ASC, "id"));
        return userRepository.findPageByName(user.getName() == null ? "%" :
                "%" + user.getName() + "%", pageable);

    }

    @RequestMapping("/new")
    public String create(ModelMap model, User user) {
        List<Department> departments = departmentRepository.findAll();
        List<Role> roles = roleRepository.findAll();

        model.addAttribute("departments", departments);
        model.addAttribute("roles", roles);
        model.addAttribute("user", user);
        return "user/new";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(User user) throws Exception {
        BCryptPasswordEncoder bcpe = new BCryptPasswordEncoder();
        user.setPassword(bcpe.encode(user.getPassword()));
        userRepository.save(user);
        logger.info("新增->ID=" + user.getId());
        return "1";
    }

    @RequestMapping(value = "/edit/{id}")
    public String update(ModelMap model, @PathVariable Long id) {


        List<Department> departments = departmentRepository.findAll();
        List<Role> roles = roleRepository.findAll();

        User user = userRepository.findOne(id);
        List<Role> userRoles = user.getRoles();

        List<Long> userRoleIds = new ArrayList<>();

        for (Role userRole : userRoles) {
            userRoleIds.add(userRole.getId());
        }

        model.addAttribute("departments", departments);
        model.addAttribute("roles", roles);

        model.addAttribute("user", user);
        model.addAttribute("userRoleIds", userRoleIds);
        return "user/edit";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(User user) throws Exception {
        userRepository.save(user);
        logger.info("修改->ID=" + user.getId());
        return "1";
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String delete(@PathVariable Long id) throws Exception {
        userRepository.delete(id);
        logger.info("删除->ID=" + id);
        return "1";
    }

}
